// Team 1 Project - Palo Alto Bicycle Club
// Author: Tom Ajayebi
// Class: COIN 71
// Filename: list_rides.js (was fetchRoute.js)
// Date Created: 04 March 09
// Purpose:
// 		Send MYSQL query to server side PHP to retrieve rows from the MySQL database.
// Modification History:
//		10 Mar 09 - Vern McGeorge - Renamed to match feature, modified includes to match directory structure, tested, and checked into SVN

// The url of the php servlet that takes an SQL query for the world db and returns an
// XML document with the reply.
var URL = "mysqlQuery.php";
//var URL = "http://ctislab.fhda.edu/ajax/mysqlQuery.php";
var myQUERY = null;
var xmlDoc  =  null;

// Result of SELECT query ,give the result back to the calling routine to do whatever they like.
function selectQueryResult(){
    jsonText = this.req.responseText;

    //DEBUG: Look at the JSON data coming back from server.
    alert(jsonText);
    
    // Update the display of the ride listing
toConsole ("list_rides - selectQueryResult 26");
		var jsonObject = eval("(" + jsonText +")");
		updateRideListing(jsonObject);
toConsole ("list_rides - selectQueryResult 29");
    return false;
}

function selectQueryResultTomsJSON(){
    xmlDoc = this.req.responseText;

    //DEBUG: Look at the XML data coming back from server.
    alert(xmlDoc);
 
    // convert returned XML into JSON
    var myJsonObject=xml2json.parser(xmlDoc,'','normal');
    
    // Update the display of the ride listing
    // updateRideListing(myJsonObject);

    // DEBUG: alert returned result in JSON
    alert(myJsonObject);
    
    // Update the display of the ride listing
toConsole ("list_rides - selectQueryResult 49");
		var jsonObject = eval("(" + myJsonObject +")");
		updateRideListing(jsonObject);
toConsole ("list_rides - selectQueryResult 52");
    return false;
}

function selectQueryResultXML(){
    xmlDoc = this.req.responseXML;
    
    // Update the display of the ride listing
toConsole ("list_rides - selectQueryResult 60");
		updateRideListing(xmlDoc);
toConsole ("list_rides - selectQueryResult 62");
    return false;
}

// Construct a SQL query for retriving fields inside mysql.
function viewGroupRidesZZZ(date){
	var days = 3;
	var msPerDay = 1000 * 60 * 60 * 24;
	var toMs = date.getMilliseconds() + (msPerDay * days);
	toConsole("date.getMilliseconds() = " + date.getMilliseconds() + ", msPerDay = " + msPerDay + ", days = " + days);
	var toDate = new Date(toMs);
	var select	= "q=SELECT id,title,city,start_point,day,date,time,leader,description,photo_url";
	var from		= " FROM bicycle.rides";
	// var where		= " WHERE date >= " + date.getFullYear() + "-" + leadingZeroes(date.getMonth()+1, 2) + "-" + leadingZeroes(date.getDate(), 2);
	var from		= " '" + date.getFullYear() + "-" + leadingZeroes(date.getMonth()+1, 2) + "-" + leadingZeroes(date.getDate(), 2) + "'";
	var to			= " '" + toDate.getFullYear() + "-" + leadingZeroes(toDate.getMonth()+1, 2) + "-" + leadingZeroes(toDate.getDate(), 2) + "'";
	var where		= " WHERE date BETWEEN" + from + " AND" + to;
	// var where		= " WHERE date >= " + leadingZeroes(date.getMonth()+1, 2) + "/" + leadingZeroes(date.getDate(), 2) + "/" + date.getFullYear();
	// var where		= " WHERE date >= " + date.toDateString();
	// var where		= " WHERE date >= " + date.getTime();
	var order		= " ORDER BY date ASC, time ASC";
	var myQUERY = select + from + where + order;
	toConsole(myQUERY);
 //call content loader with the query constructed.
 contentLoader = new net.ContentLoader(URL, selectQueryResult, errorFunction, "POST", myQUERY);
}
function viewGroupRides(date){
	var days = 3;
	var msPerDay = 1000 * 60 * 60 * 24;
	var fromMs = date.getTime(); //  - (msPerDay * days);
	var toMs = date.getTime() + (msPerDay * days);
	// toConsole("date.getTime() = " + date.getTime() + ", msPerDay = " + msPerDay + ", days = " + days);
	var fromDate = new Date(fromMs);
	var toDate = new Date(toMs);
	var select	= "q=SELECT id,title,city,start_point,day,date,time,leader,description,photo_url";
	var from		= " FROM bicycle.rides";
	var fromStr	= " '" + fromDate.getFullYear() + "-" + leadingZeroes(fromDate.getMonth()+1, 2) + "-" + leadingZeroes(fromDate.getDate(), 2) + "'";
	var toStr		= " '" + toDate.getFullYear() + "-" + leadingZeroes(toDate.getMonth()+1, 2) + "-" + leadingZeroes(toDate.getDate(), 2) + "'";
	var where		= " WHERE date BETWEEN" + fromStr + " AND" + toStr;
	var order		= " ORDER BY date ASC, time ASC";
	var myQUERY = select + from + where + order;
	toConsole(myQUERY);
 //call content loader with the query constructed.
 contentLoader = new net.ContentLoader(URL, selectQueryResult, errorFunction, "POST", myQUERY);
}

function leadingZeroes(value, width) {
	var s = "0000000000" + value;
	s = s.substr(s.length-width, s.length);
	return s;
}



// Result of INSERT query, just give a message back to user if the insert succeed.
function insertQueryResult(){
    xmlDoc = this.req.responseText;

    //DEBUG: display returned xml for debug
    alert(xmlDoc);

}


// INSERT Operation: Grab user inputed data and INSERT it into mysql DB table
function sendInsertQuery(){

    // get field values from HTML page to construct INSERT query
    var title_value = document.getElementById("title").firstChild.value  ;
    var city_value = document.getElementById("city").firstChild.value ;
    var start_point_value = document.getElementById("start_point").firstChild.value ;
    var day_value = document.getElementById("day").firstChild.value ;
    var date_value = document.getElementById("date").firstChild.value ;
    var time_value = document.getElementById("time").firstChild.value ;
    var leader_value = document.getElementById("leader").firstChild.value ;
    var description_value = document.getElementById("description").firstChild.value ;
    var photo_url_value = document.getElementById("photo_url").firstChild.value ;

   //DEBUG:  alert values inputed by user for INSERT Operation
   /*alert("title_value="+title_value+
         "\ncity_value="+city_value+
         "\nstart_point_value="+start_point_value+
         "\nday_value="+day_value+
         "\ndate_value="+date_value+
         "\ntime_value="+time_value+
         "\nleader_value="+leader_value+
         "\ndescription_value="+description_value+
         "\nphoto_url_value="+photo_url_value);
   */

    // Check to see if all the fields are inputed by user.
    if ((title_value == "")  || (city_value == "" )       || (start_point_value == "") ||
        (day_value == "")    || (date_value == "")        || (time_value == "")        ||
        (leader_value == "") || (description_value == "") || (photo_url_value == "")) {
         alert("All need to be input, no NULL value is permitted");
    }
    else {
        myQUERY = "q=INSERT INTO bicycle.rides (title,city,start_point,day,date,time,leader,description,photo_url) VALUES ('"+title_value+"','"+city_value+"','"+start_point_value+"','"+day_value+"','"+date_value+"','"+time_value+"','"+leader_value+"','"+description_value+"','"+photo_url_value+"')";
        contentLoader = new net.ContentLoader(URL, insertQueryResult, errorFunction, "POST", myQUERY);
        alert("success.");
    }
    return false;
}

// Callback to initialize ride list with rides starting today.
function getRidesForToday() {
	// toConsole("getting rides for today");
	var today = new Date();
	viewGroupRides (today);   // BUT, not until I get this working.
	return true;
}

// On page load, get the rides for today.
// OnPageLoad.handler.callThis(getRidesForToday);
jQuery.event.add( window, "load", getRidesForToday );
